<template>
  <view class="gg-upload-img-wrap">
    <block v-if="uploadType=='big'">
      <view class="gg-upload-imgbig_view" @tap="imgChoose" v-if=" localSrc =='' ">
        <view class="gg-upload-imgbig-left">
          <view class="gg-upload-imgbig-left__title">{{label}}</view>
          <view>{{uploadTip.dimension}}</view>
          <view>{{uploadTip.format}}</view>
          <view>{{uploadTip.size}}</view>
        </view>
        <view class="gg-upload-imgbig-right">
          <view class="gg-upload-imgbig-right__upload">
            <gg-icons type="action-quan-plus-filled" size="36" color="#999999"></gg-icons>
            <view>添加图片</view>
          </view>
        </view>
      </view>
      <view class="gg-upload-imgbig_view gg-upload-img_noborder" v-else>
        <view class="gg-upload-img__bd bigimg">
          <image class="gg-upload-img-preview" lazy-load="true" mode="aspectFit" :src=" localSrc[0] " @tap="imgShowbig" :data-src="localSrc[0]">
          </image>
          <gg-icons class="gg-uoload-img-remove" type="action-quan-cha" size="20" color="#FF0101" @tap="imgRemove(0)" v-if="!disabled"></gg-icons>
        </view>
      </view>
    </block>
    <block v-else>
      <view class="gg-upload-img-hd">{{label}}</view>
      <view class="gg-upload-imgmore_img">
        <block v-if=" localSrc != ''">
          <block v-for="(item, index) in localSrc" :key="index">
            <view class="gg-upload-img__bd" :class="(index + 1) % 3 !== 0 ? 'gg-upload-img_img__body__mar' : ''">
              <image class="gg-upload-img-preview" lazy-load="true" mode="aspectFit" :src="item" @tap="imgShowbig" :data-src="item"></image>
              <gg-icons class="gg-uoload-img-remove" type="action-quan-cha" size="20" color="#FF0101" @tap="imgRemove(index)" v-if="!disabled">
              </gg-icons>
            </view>
          </block>
        </block>
        <view class="gg-upload-img__bd" v-if=" localSrc.length < allowUploadNum ">
          <view class="gg-upload-img-choose" @tap="imgChoose">
            <gg-icons :size="settAdd.size" :color="settAdd.color" :type="settAdd.icon"></gg-icons>
            <view>可{{settAdd.text}}{{surplusUploadNum}}张</view>
          </view>
        </view>
      </view>
    </block>
  </view>
</template>
<script>
export default {
  name: "GgUploadImg",
  components: {
  },
  props: {
    label: {
      type: [String],
      default: ""
    },
    // 风格：one单图，more多图，big大图
    uploadType: {
      type: String,
      default: "one"
    },
    uploadTip: {
      type: Object,
      default() {
        return {
          dimension: '长*宽：750*375像素;',
          format: '格式：jpg/png;',
          size: '大小：小于2MB'
        }
      }
    },
    // 提示
    tip: {
      type: String,
      default: ""
    },
    //默认输入框
    value: {
      type: [Array, Object, String],
      default() {
        return []
      }
    },
    src: {
      type: [Array, Object, String],
      default(newVal) {
        return []
      }
    },
    maxlength: {
      type: [String, Number],
      default: 1
    },
    addType: {
      type: String,
      default: 'add'
    },
    filename: {
      type: String,
      default: ''
    },
    uploadParam: {
      type: Object,
      default: () => {
        return {}
      }
    },
    apiFunc: {
      type: Function,
      default() {
        return null;
      }
    },
    disabled: {
      type: [Boolean, String],
      default() {
        return false;
      }
    },
  },
  data() {
    return {
      localVal: null,
      localSrc: [],
      settAdd: {
        text: '添加',
        //icon颜色
        color: '#999999',
        //图标类型，默认相机
        icon: this.addType == 'camera' ? 'media-camera-filled' : 'media-image-filled',
        // 图标
        size: 26,
      },
      // 每次选择图片数量
      chooseNum: 1,
      // 剩余允许上传数量
      allowUploadNum: 1,
      surplusUploadNum: 1,
    };
  },
  watch: {
    value(newVal) {
      this.localVal = newVal;
    },
    src(newVal) {
      //   this.localSrc = this._dealSrc(newVal);
      this._dealNum();
    },
  },
  created: function () {
    this.localVal = this.value;
    this.localSrc = this._dealSrc(this.src);
    this.allowUploadNum = parseInt(this.maxlength);
    this._dealNum();
  },
  methods: {
    _dealNum() {
      this.surplusUploadNum = (this.allowUploadNum - (this.localSrc.length || 0));
    },
    _dealSrc(oldSrc) {
      let newSrc = [];
      if (this.uploadType == 'big') {
        if ((typeof oldSrc) == 'string') {
          newSrc.push(oldSrc);
        }
      } else if (this.uploadType == 'one') {
        if ((typeof oldSrc) == 'string') {
          newSrc.push(oldSrc);
        }
      } else {
        if ((typeof oldSrc) == 'object') {
          return oldSrc;
        }
      }
      return newSrc;
    },
    /** 图片选择 ：从本地相册选择图片或使用相机拍照 */
    // async
    async _chooseImage(type, source = 'album') {
      uni.chooseImage({
        count: this.surplusUploadNum, // 选择照片的总数
        sizeType: ['compressed', 'original'], // 可选择原图或压缩后的图片
        sizeType: ['compressed'], // 默认二者都有,original 原图，compressed 压缩图
        sourceType: ['album', 'camera'], // 可选择性开放访问相册、相机
        sourceType: [source], // 从相册选择 album 从相册选图，camera 使用相机
        success: (res) => {

          // console.warn(res.tempFilePaths);
          // console.warn(res.tempFiles[0].path);

          let uploadChooseNum = res.tempFilePaths.length;
          let uploadCurrIndex = 0; //当前index
          let uploadAlreadyNum = 0; //当前已上传页数

          if (uploadChooseNum >= 9) {
            uni.showToast({ 'icon': 'none', 'title': '超出9张~' });
            return false;
          }
          if (uploadChooseNum > this.surplusUploadNum) {
            uni.showToast({ 'icon': 'none', 'title': '已超过剩余数量~' });
            return false;
          }

          var timer = setInterval(() => {
            if (this.surplusUploadNum == 0) {
              uni.showToast({
                icon: 'none',
                title: '已上传',
                duration: 1000,
                mask: true
              });
              uni.hideToast();
              uni.hideLoading();
              // TODO 追加到数组
              clearInterval(timer);
            } else if (uploadAlreadyNum < uploadChooseNum) {
              uploadAlreadyNum++;
              // TODO 上传
              uni.showToast({
                icon: 'loading',
                title: '正在上传(' + uploadAlreadyNum + '/' + uploadChooseNum + ')',
                duration: 3000000,
                mask: true
              });
              this._uploadImage(res.tempFilePaths[uploadCurrIndex]);
              uploadCurrIndex++;
              this.surplusUploadNum--;
            } else {
              uni.hideToast();
              uni.hideLoading();
            }
          }, 1000);

          // for (let [index, val] of res.tempFilePaths.entries()) {
          //   this._uploadImage(val); //上传图片
          //   this.surplusUploadNum--;
          // }
        },
        fail: (res) => {
        },
      });
    },
    /** 图片验证 */
    _imgCheck(imgItem) {
      let imgSize = imgItem.size || 0;
      if (imgSize > 2048) {
      }
    },
    /** 图片上传 */
    _uploadImage(tempFilePaths, type) {
      let filename = this.filename || 'uni-upload';// 'file_name'
      let uploadParam = Object.assign({}, {
        postType: 'create',
        file_name: filename,
        savesign: 'uni-upload',
      }, this.uploadParam);

      //将本地资源上传到开发者服务器，客户端发起一个 POST 请求，其中 content-type 为 multipart/form-data。
      this.$request.flagUpImg('SDKS_USE_FILE_UPLOAD_IMG', {
        //要上传文件资源的路径。
        filePath: tempFilePaths,
        //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
        name: filename,
        //HTTP 请求中其他额外的 form data
        formData: uploadParam
      }).then((uploadRes) => {
        // let resData = JSON.parse(uploadRes.data);
        let resData = uploadRes.data || {};
        if (this.uploadType == 'more') {
          //图集
          if (this.localSrc.length >= 9) return;
          this.localSrc.push(resData.img_cdn);
          this.localVal.push(resData.img_time);
        } else {
          //单图
          this.localSrc.push(resData.img_cdn);
          this.localVal = resData.img_time;
        }
        this.$emit('input', this.localVal);
        // this.$forceUpdate();
      }).catch((err) => {
        uni.hideLoading();
      });
    },
    // 删除引客卷图片
    imgRemove(imgIndex) {
      if (this.uploadType == 'more') {
        this.localSrc.splice(imgIndex, 1);
        this.localVal.splice(imgIndex, 1);
      } else {
        this.localSrc.splice(imgIndex, 1);
        this.localVal = '';
      }
      this.surplusUploadNum++;
    },
    // 预览大图
    imgShowbig(src) {
      let srcUrl = src.currentTarget.dataset.src;
      uni.previewImage({
        urls: [srcUrl]
        // current: srcUrl,
      });
    },
    imgChoose() {
      if (!this.$request.flagUpImg) {
        uni.showToast({
          icon: "none",
          title: '上传方法错误',
          duration: 2000,
        });
        return false;
      }
      if (this.uploadType != 'more') {
        this.allowUploadNum = 1;
      }
      if ((this.localSrc.length + 1) > this.allowUploadNum) {
        uni.showToast({
          icon: "none",
          title: '超出图片上传个数...',
          duration: 2000,
        });
        return false;
      }
      return new Promise((resolve, reject) => {
        this._chooseImage();
        // this.$emit('input', this.localVal);
      })
    },
  }
};
</script>
<style>
.gg-upload-img-wrap {
  padding: 10px 15px;
  background: #fff !important;
}

.gg-upload-img-hd {
  color: #181818;
  font-size: 15px;
  margin-bottom: 10px;
}
/** 选择 */
.gg-upload-img-choose {
  font-size: 12px;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  justify-content: center;
  color: #888888;
}
/** 上传后预览 */
.gg-upload-img-preview {
  width: 100%;
  height: 100%;
  border-radius: 10px;
}
/** 移除 */
.gg-uoload-img-remove {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 997;
  background: #fff;
  border-radius: 50%;
}
/* .gg-upload-img-choose icon {
  font-size: 12px;
  margin-bottom: 10px;
  color: #c8c7cc;
} */
.gg-upload-imgmore_img {
  display: flex;
  flex-wrap: wrap;
}

.gg-upload-img__bd {
  width: 88px;
  height: 66px;
  border: 1px dashed #99999999;
  border-radius: 10px;
  margin-bottom: 10px;
  position: relative;
}

.gg-upload-img__bd.bigimg {
  width: 100%;
  height: 100%;
}

.gg-upload-img_img__body__mar {
  margin-right: 45rpx;
}

.gg-upload-img_noborder {
  border: 0px !important;
  padding: 0px !important;
}
.gg-upload-imgbig_view {
  height: 345rpx;
  padding: 20rpx 42rpx;
  display: flex;
  border: 2rpx dashed #c7c7c7;
  color: #888888;
  border-radius: 10rpx;
  justify-content: space-between;
  font-size: 24rpx;
}
.gg-upload-imgbig-left {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.gg-upload-imgbig-left view {
  max-width: 400rpx;
  overflow: hidden;
  text-overflow: ellipsis;
}
.gg-upload-imgbig-left__title {
  color: #181818;
  font-size: 34rpx;
  margin-bottom: 10rpx;
}
.gg-upload-imgbig-right {
  display: flex;
  align-items: center;
}
.gg-upload-imgbig-right__upload {
  border-radius: 20rpx;
  background: #e5e5e1;
  width: 180rpx;
  height: 180rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
</style>